<script setup>
import {
  userRestGetByUsernameService,
  userRestGetEmailCodeService,
  userRestPwdService,
  userRestVerifyEmailCodeService
} from '@/api/user'
import { useRouter } from 'vue-router'
import { ZlMessage } from '@/utils/message'
import { useUserStore } from '@/stores'

import { ref } from 'vue'

const router = useRouter()
const userStore = useUserStore()
const current = ref(1)

const emailForm = ref({ email: '', emailCode: '' })

// 找回的账号名
const username = ref('')

// // 找回的账号对应绑定的邮箱
// const email = ref('')

// // 邮箱验证码
// const emailCode = ref('')

// 步骤一的提示
const step1Msg = ref('')
const step2Msg = ref('')

// 身份认证成功的 key
const key = ref('')

// 获取到的用户
const userinfo = ref({})

// 新用户表单输入的密码
const newUserinfoForm = ref({ password: '', confirmPassword: '' })
const newUserinfoRef = ref()
// 邮箱校验规则
const newUserinfoRules = {
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value.length < 10) {
          return callback(new Error('密码长度最少为 10 个字符。'))
        }

        if (value.length > 20) {
          return callback(new Error('密码长度最长为 20 个字符。'))
        }

        // 创建正则表达式来匹配至少一个英文字符和一个数字字符
        const hasEnglishChar = /[a-zA-Z]/.test(value)
        const hasNumberChar = /[0-9]/.test(value)
        if (!(hasEnglishChar && hasNumberChar)) {
          return callback(new Error('密码最少包含一个英文字符和一个数字字符！'))
        }
        if (value.split(' ').length > 1 || value.trim() !== value) {
          return callback(new Error('密码不能包含空格字符.'))
        }
        callback()
      }
    }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value != newUserinfoForm.value.password) {
          callback(new Error('两次输入密码不一致！'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 邮箱校验规则
const rules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
        if (!emailRegex.test(value)) {
          callback(new Error('请输入合法的邮箱！'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}
const emailRef = ref()

// 上一步
const onPrev = () => {
  current.value = Math.max(1, current.value - 1)
}

// 下一步
const onNext = async () => {
  if (current.value == 1) {
    if (username.value == '' || username.value.length < 9) {
      step1Msg.value = '请输入正确的账号'
      return
    }
    // 提交账号给后端, 判断该账号是否存在
    const res = await userRestGetByUsernameService(username.value)
    if (res.data.data.userId !== null) {
      userinfo.value = res.data.data
      step1Msg.value = ''
      current.value = Math.min(3, current.value + 1)
    } else {
      step1Msg.value = '账号不存在!'
      return
    }
  } else if (current.value == 2) {
    await emailRef.value.validate()
    console.log(emailForm.value.emailCode)

    if (emailForm.value.emailCode == '') {
      ZlMessage.error('请输入验证码')
      return
    }
    const res = await userRestVerifyEmailCodeService(emailForm.value)
    if (res.data.code !== 200) {
      ZlMessage.warning(res.data.msg)
      return
    }
    key.value = res.data.data
    current.value = Math.min(3, current.value + 1)
  } else if (current.value == 3) {
    // 修改密码
    await newUserinfoRef.value.validate()
    // 提交数据给后端
    userinfo.value.password = newUserinfoForm.value.password
    userinfo.value.email = emailForm.value.email

    const res = await userRestPwdService(userinfo.value, key.value)
    ZlMessage.success(res.data.msg)
    // 清空 store 数据
    userStore.exit()
    router.push('/login')
  }
}

const setCurrent = (cur) => {
  current.value = cur
}

// 获取邮箱验证码
const getEmailCode = async () => {
  await emailRef.value.validate()
  const res = await userRestGetEmailCodeService(
    username.value,
    emailForm.value.email
  )
  if (res.data.code != 200) {
    ZlMessage.warning(res.data.msg)
    return
  }
  ZlMessage.success(res.data.msg)
}
</script>

<template>
  <div style="display: flex; height: 100vh; align-items: center">
    <div style="width: 500px; margin: 0 auto">
      <div
        :style="{
          width: '100%',
          textAlign: 'center',
          height: '200px',
          color: '#C2C7CC'
        }"
      >
        <!-- 第一步输入忘记密码的账号 -->
        <div v-if="current == 1">
          <el-text tag="p" style="text-align: left"
            >请输入忘记密码的账号:</el-text
          >
          <null-box size="30"></null-box>
          <el-form-item>
            <el-input
              v-model="username"
              placeholder="账号"
              size="large"
            ></el-input>
          </el-form-item>
          <el-text
            tag="p"
            size="small"
            style="text-align: left"
            type="danger"
            >{{ step1Msg }}</el-text
          >
        </div>

        <!-- 第二步输入该账号绑定的邮箱 -->
        <div v-if="current == 2">
          <el-text tag="p" style="text-align: left"
            >请输入{{ userinfo.username }}账号绑定的邮箱:</el-text
          >
          <null-box size="30"></null-box>
          <el-form ref="emailRef" :rules="rules" :model="emailForm">
            <el-form-item prop="email">
              <el-input
                v-model="emailForm.email"
                placeholder="邮箱"
                size="large"
                autocomplete="new-password"
              ></el-input>
            </el-form-item>
            <null-box size="10"></null-box>
            <el-row style="justify-content: space-between">
              <el-form-item>
                <el-input
                  v-model="emailForm.emailCode"
                  placeholder="邮箱验证码"
                  size="large"
                  autocomplete="new-password"
                ></el-input>
              </el-form-item>
              <el-button style="height: 40px" @click="getEmailCode"
                >获取验证码</el-button
              >
            </el-row>
          </el-form>

          <el-text
            tag="p"
            size="small"
            style="text-align: left"
            type="danger"
            >{{ step2Msg }}</el-text
          >
        </div>
        <!-- 第三步更改密码 -->
        <div v-if="current == 3">
          <el-text tag="p" style="text-align: left" type="success"
            >认证已通过，请在 5 分钟内完成修改密码！</el-text
          >
          <null-box size="20"></null-box>
          <el-form
            ref="newUserinfoRef"
            :rules="newUserinfoRules"
            :model="newUserinfoForm"
          >
            <el-form-item prop="password">
              <el-input
                v-model="newUserinfoForm.password"
                placeholder="新密码"
                size="large"
                auto-complete="off"
                type="password"
              ></el-input>
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input
                v-model="newUserinfoForm.confirmPassword"
                placeholder="确认密码"
                size="large"
                auto-complete="off"
                type="password"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <a-steps :changeable="false" :current="current" @change="setCurrent">
        <a-step description="步骤1">确认账号</a-step>
        <a-step description="步骤2">核实绑定邮箱</a-step>
        <a-step description="步骤3">更改密码</a-step>
      </a-steps>
      <div style="margin-top: 20px; text-align: center">
        <a-space size="large">
          <a-button type="secondary" :disabled="current <= 1" @click="onPrev">
            上一步
          </a-button>
          <a-button type="primary" :disabled="current > 3" @click="onNext">
            {{ current < 3 ? '下一步' : '修改' }}
          </a-button>
        </a-space>
      </div>
    </div>
  </div>
</template>
